package com.example.clientdemo.Utils;

import cn.hutool.http.HttpRequest;

/**
 * webService调用工具类
 */
public class WebServiceUtil {

    /**
     * webService调用(xml-xml)
     * @param url - url
     * @param xmlBody xml请求
     * @return xml格式响应
     */
    public static String webServiceRequestXmlToXml(String url, String xmlBody) {
        return HttpRequest.post(url)
                .body(xmlBody)
                .header("Content-Type", "text/xml; charset=utf-8")
                .execute()
                .body();
    }

    /**
     * webService调用(body-body)
     * @param url - url
     * @param xmlBody xmlBean请求对象
     * @param responseClass xmlBean响应对象class
     * @return xmlBean响应对象
     */
    public static <E, T> T webServiceRequestBodyToBody(String url, E xmlBody, Class<T> responseClass) {
        // 1、构建xml参数
        String request = XStreamXmlBeanUtil.toXml(xmlBody);
        // 2、调用post请求，请求体为xml
        String response = webServiceRequestXmlToXml(url, request);
        // 3、响应解析
        return XStreamXmlBeanUtil.fromXml(response, responseClass);
    }

    /**
     * webService调用(xml-body)
     * @param url - url
     * @param xmlBody xml请求
     * @param responseClass xmlBean响应对象class
     * @return xmlBean响应对象
     */
    public static <T> T webServiceRequestXmlToBody(String url, String xmlBody, Class<T> responseClass) {
        return XStreamXmlBeanUtil.fromXml(webServiceRequestXmlToXml(url, xmlBody), responseClass);
    }

    /**
     * webService调用(body-xml)
     * @param url - url
     * @param xmlBody xmlBean请求对象
     * @return xml格式响应
     */
    public static <T> String webServiceRequestBodyToXml(String url, T xmlBody) {
        return webServiceRequestXmlToXml(url, XStreamXmlBeanUtil.toXml(xmlBody));
    }
}
